package com.findMoneyGame.server {
	import flash.events.Event;
	import flash.net.URLVariables;

	import com.adobe.serialization.json.JSON;

	import com.findMoneyGame.server.ServerBridge;
	import com.findMoneyGame.server.IServerFacade;
	import com.findMoneyGame.models.UserData;

	public class ServerFacade implements IServerFacade {
		private static const URL_BASE = "http://myconstru.w.pw/game/";
		private static const USER_EXISTS_URL = URL_BASE + "userExists.php";
		private static const NEW_USER_URL = URL_BASE + "newUser.php";
		private static const GET_USER_URL = URL_BASE + "getUser.php";
		private static const POST_USER_URL = URL_BASE + "postUser.php";
		private static const FETCH_LEVELS_REQUEST = URL_BASE + "gameLevels.php";
		private static const FETCH_LEVEL_REQUEST = URL_BASE + "fetchGameLevel.php"

		private var server = new ServerBridge();

		public function get imageBytesTotal () : int { return server.imageBytesTotal; }
		public function get imageBytesLoaded () : int { return server.imageBytesLoaded; }
		public function get bytesTotal () : int { return server.urlRequestBytesTotal; }
		public function get bytesLoaded () : int { return server.urlRequestBytesLoaded; }

		public function beginLoadImage (url : String, complete : Function, error : Function) { server.beginLoadImage(url, complete, error); }

		public function beginCheckUserExists (id : int, complete : Function, error : Function) {
			var reqComplete = function (data : *) {
				trace('Ответ на запрос проверить существование пользователя с id = ' + id + ' : ' + data)
				if (String(data).length == 0) {
					error(new Event('emptyAnswer'));
				} else {
					var decoded = JSON.decode(data).toString();
					if (isNaN(decoded)) {
						error(null);
					} else {
						complete(int(decoded) == 1);
					}
				}
			};
			var url = USER_EXISTS_URL + '?vkId=' + id + '&' + Math.random();
			server.beginGetUrlRequest(url, reqComplete, error);
		}
		public function beginCreateNewUser (id : int, complete : Function, error : Function) {
			var reqComplete = function (data : *) {
				trace('Ответ на запрос создать нового пользователя с id = ' + id + ' : ' + data)
				if (String(data).length == 0) {
					error(new Event('emptyAnswer'));
				} else{
					var result = JSON.decode(data);
					if (isNaN(result)) {
						error(null);
					} else if (int(result) == 1) {
						complete();
					} else {
						error(null);
					}
				}
			}
			var reqVariables = new URLVariables();
			reqVariables['vkId'] = id;
			server.beginPostUrlRequest(NEW_USER_URL, reqVariables, reqComplete, error);
		}
		public function beginFetchUserData (id : int, complete : Function, error : Function) {
			var reqComplete = function (data : *) {
				trace('Ответ на запрос получить данные пользователя с id = ' + id + ' : ' + data)
				if (String(data).length == 0) {
					error(new Event('emptyAnswer'));
				} else{
					var decoded = JSON.decode(data);
					var userData = new Object();
					
					userData.level = int(decoded.level);
					userData.fastCompletedLevelCount = int(decoded.fastCompletedLevelCount);
					userData.achievement = int(decoded.achievement);
					
					userData.moneyCount = int(decoded.money_count);
					userData.moneyBought = int(decoded.money_bought);
					userData.moneySpent = int(decoded.money_spent);
					
					userData.timeBonusIndex = int(decoded.bonus_time);
					userData.loupeBonusIndex = Number(decoded.loupe_scale);
					userData.hintBonusIndex = int(decoded.hint_radius);
					
					complete(userData);
				}
			};
			var url = GET_USER_URL + '?vkId=' + id + '&' + Math.random();
			server.beginGetUrlRequest(url, reqComplete, error);
		}
		public function beginSaveUserData (userData : UserData, complete : Function, error : Function) {
			var reqComplete = function (data : *) {
				trace('Ответ на запрос сохранить данные пользователя с id = ' + userData.id + ' : ' + data)
				if (String(data).length == 0) {
					error(new Event('emptyAnswer'));
				} else {
					var result = JSON.decode(data);
					if (isNaN(result)) {
						error(null);
					} else if (int(result) == 1) {
						complete();
					} else {
						error(null);
					}
				}
			}
			var reqVariables = new URLVariables();
			reqVariables['vk_id'] = userData.id;
			
			reqVariables['level'] = userData.level;
			reqVariables['fastCompletedLevelCount'] = userData.fastCompletedLevelCount;
			reqVariables['achievement'] = userData.achievement;

			reqVariables['money_count'] = userData.moneyCount;
			reqVariables['money_bought'] = userData.moneyBought;
			reqVariables['money_spent'] = userData.moneySpent;
			
			reqVariables['bonus_time'] = userData.timeBonusIndex;
			reqVariables['loupe_scale'] = userData.loupeBonusIndex;
			reqVariables['hint_radius'] = userData.hintBonusIndex;
			
			server.beginPostUrlRequest(POST_USER_URL, reqVariables, reqComplete, error);
		}
		public function beginFetchGameLevel (level : int, complete : Function, error : Function) {
			var reqComplete = function (data : *) {
				trace('Ответ на запрос о получении данных об уровне номер ' + level + ': ' + data);
				if (String(data).length == 0) {
					error(new Event('emptyAnswer'));
				} else {
					complete(JSON.decode(data));
				}
			};
			var url = FETCH_LEVEL_REQUEST + '?levelIndex=' + level + '&' + Math.random();
			server.beginGetUrlRequest(url, reqComplete, error);
		}
	}
}